package com.elite.groovy.callback

import com.elite.groovy.kh.KHDBConfig
import com.elite.groovy.util.EliteBean
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils
import org.springframework.jdbc.core.JdbcTemplate
import java.nio.charset.StandardCharsets;
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * @Title:知识产权数据推送-假货举报工单
 * @Description:
 * @Param:
 * @return:
 * @Author:Rick
 * @Date: 2024/09/24
 */

public class apiAutoPushClue implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiAutoPushClue.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        long startTime = System.currentTimeMillis();
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        //扫假货工单数据
        //检查推送数据
        String PustSQL='''select 
                                    OBJECTIVE_GUID as externalId,
                                    o.WORKORDERID AS clueNo,
                                    sw.WORKORDERTYPE2DESC AS clueSource,
                                    tb.address as belongArea,
                                    concat(CP.PROVINCE_DESC,'-',cc.CITY_DESC) AS belongCity,
                                    '门店' AS reportType,
                                    '假货' as reportProductType,
                                    TB.fakes_store  AS reportTargetName,
                                    concat(IFNULL(TB.fakes_address,''),IFNULL(TB.fakes_address_details,'')) AS reportAddress,
                                    TB.remark AS remark,
                                    TB.customername AS submitByName ,
                                    TB.mobile AS submitBy , 
                                    '' AS submitOrgName,
                                    O.CREATEDDATE AS submitDate,
                                    TB.mobile AS submitContact,
                                    TB.fakes_account AS reportAccount,
									TB.fakes_link as reportProductUrl,
                                    '' as dealBy
                                from objective O 
                                LEFT JOIN tabcworkorder tb on O.OBJECTIVE_GUID=tb.RELATION_ID
                                LEFT JOIN sys_workordertype2 SW ON O.workordertype2=SW.WORKORDERTYPE2_ID
                                LEFT JOIN c_province CP ON CP.PROVINCE_ID=tb.province
                                LEFT JOIN c_city cc ON cc.CITY_ID=tb.city
                                where o.map_id='0N6WDG' and o.uploadstatus is null limit 10 '''

        List<Map<String, Object>> PustSqlList = jt.queryForList(PustSQL);

        // 获取任务配置基础数据
       // String callURL = KHDBConfig.getAPIURL(eliteBean, "");
       // log.debug("接口地址:" + callURL);
        String URL = KHDBConfig.getAPIURL(eliteBean, "SynchronizationClue");
        String URL1 = URL+"type=0"; //线下
        String URL2 = URL+"type=1"; //线上

        String UpdateSQL = ''' update objective set uploadstatus='1' where objective_guid = ? '''
        for(int i = 0 ; i < PustSqlList.size();i++){

            try{
                Map<String, Object> Mapdata = PustSqlList[i]
                if(PustSqlList[i].get("clueSource")=='线下实体销售'){
                    dohttp1(jt,Mapdata,URL1);
                }else if(PustSqlList[i].get("clueSource")=='网购、社交等线上销售'){
                    dohttp2(jt,Mapdata,URL2);
                }else{
                    log.debug("非正常数据，不推送");
                }
                //修改数据
                jt.update(UpdateSQL,PustSqlList[i].get("externalId"));
            }catch (Exception e){
                log.debug(e.toString());
            }



        }



    }




/**
 *
 * @Title: 线下接口调用
 *
 */

    //推送数据
    public static String dohttp1(JdbcTemplate jt,Map<String, Object> Mapdata,String URL1) {

                // 创建 HttpClient 实例
                HttpClient client = HttpClients.createDefault();
                // 定义 UTF-8 的 ContentType
                ContentType textContentType = ContentType.create("text/plain", "UTF-8");

                // 创建多部分表单请求体
                 MultipartEntityBuilder builder = MultipartEntityBuilder.create()
                        .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                        .addPart("externalId", new StringBody(Mapdata.get("externalId").toString(), textContentType))                 //唯一标识
                        .addPart("clueNo", new StringBody(Mapdata.get("clueNo").toString(), textContentType))                         //线索编号
                        .addPart("belongArea", new StringBody(Mapdata.get("belongArea").toString(), textContentType))                 //所属大区
                        .addPart("belongCity", new StringBody(Mapdata.get("belongCity").toString(), textContentType))                 //省份-城市
                         .addPart("clueSource", new StringBody("客诉系统", textContentType))                                            //线索来源
                        .addPart("reportType", new StringBody("门店", textContentType))                                                //举报类型
                        .addPart("reportProductType", new StringBody("假货", textContentType))                                         //举报产品类型
                        .addPart("reportTargetName", new StringBody(Mapdata.get("reportTargetName").toString(), textContentType))      //举报店名
                        .addPart("reportAddress", new StringBody(Mapdata.get("reportAddress").toString(), textContentType))            //举报详细地址
                        .addPart("remark", new StringBody(Mapdata.get("remark").toString(), textContentType))                           //备注
                        .addPart("submitBy", new StringBody(Mapdata.get("submitBy").toString(), textContentType))                       //提报帐号
                        .addPart("submitByName", new StringBody(Mapdata.get("submitByName").toString(), textContentType))               //提报人
                        .addPart("submitOrgName", new StringBody(Mapdata.get("submitOrgName").toString(), textContentType))             //提报部门  -传个空
                        .addPart("submitContact", new StringBody(Mapdata.get("submitContact").toString(), textContentType))             //联系方式
                        .addPart("submitDate", new StringBody(Mapdata.get("submitDate").toString(), textContentType))                    //提报日期
                        .addPart("dealBy", new StringBody(Mapdata.get("dealBy").toString(), textContentType));                          //受理人帐号 -传个空


                        // 检查工单文件
                        String FileSQL =  ''' select PATH,UPLOAD_CLASS2_ID from uploadlist where  GUID=? '''
                        List<Map<String, Object>> FileSQLSqlList = jt.queryForList(FileSQL,Mapdata.get("clueNo").toString());
                        File file1,file2;
                        for(int j = 0 ; j < FileSQLSqlList.size();j++){
                            // 创建文件对象
                            String FilePatch = "/nas/davco_cc/ngs/"+FileSQLSqlList[j].get("PATH");
                            String FileType = FileSQLSqlList[j].get("UPLOAD_CLASS2_ID");
                            if(FileType.equals("FAKES1")&&file1==null){
                                 file1 = new File(FilePatch); // 替换为你的文件路径
                                builder.addPart("offlineDoorPhoto", new FileBody(file1, textContentType));                              //门店图片
                            }else if(FileType.equals("FAKES2")&&file2==null){
                                 file2 = new File(FilePatch); // 替换为你的文件路径
                                builder.addPart("offlineProductPhoto", new FileBody(file2, textContentType));                           //产品图片
                            }
                        }


                        HttpEntity entity = builder.build();



                        // 创建 POST 请求
                        HttpPost post = new HttpPost(URL1); // 替换为你的 API 地址
                        post.setEntity(entity);
                        post.addHeader("P-AUTH-TOKEN", "1ADyBSGt@67012792");

                        // 发送请求并获取响应
                        HttpResponse response1 = client.execute(post);
                        int statusCode = response1.getStatusLine().getStatusCode();
                        if (statusCode == 200) {
                            String responseBody = EntityUtils.toString(response1.getEntity());
                            log.debug("调取结果成功: " + responseBody);
                        } else {
                            log.debug("调取结果失败: " + statusCode);
                        }



    }







/**
 *
 * @Title: 线上接口调用
 *
 */

    //推送数据
    public static String dohttp2(JdbcTemplate jt,Map<String, Object> Mapdata,String URL2) {

        // 创建 HttpClient 实例
        HttpClient client = HttpClients.createDefault();


        // 定义 UTF-8 的 ContentType
        ContentType textContentType = ContentType.create("text/plain", "UTF-8");

        // 创建多部分表单请求体
         MultipartEntityBuilder builder = MultipartEntityBuilder.create()
                .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                .addPart("externalId", new StringBody(Mapdata.get("externalId").toString(), textContentType))                        //唯一标识
                .addPart("clueNo", new StringBody(Mapdata.get("clueNo").toString(), textContentType))                                //线索编号
                .addPart("clueSource", new StringBody("客诉系统", textContentType))                                                   //线索来源
                .addPart("belongArea", new StringBody(Mapdata.get("belongArea").toString(), textContentType))                        //所属大区
                 .addPart("reportType", new StringBody("社交网络SNS", textContentType))                                                      //举报类型
                .addPart("reportProductType", new StringBody("假货", textContentType))                                                //举报产品类型
                .addPart("reportAccount", new StringBody(Mapdata.get("reportAccount").toString(), textContentType))                                                 //举报帐号
                .addPart("reportProductUrl", new StringBody(Mapdata.get("reportProductUrl").toString(), textContentType))                 //举报产品链接
                .addPart("remark", new StringBody(Mapdata.get("remark").toString(), textContentType))                                 //备注
                .addPart("submitBy", new StringBody(Mapdata.get("submitBy").toString(), textContentType))                                  //提报人帐号
                .addPart("submitByName", new StringBody(Mapdata.get("submitByName").toString(), textContentType))                                  //提报人名称
                .addPart("submitContact", new StringBody(Mapdata.get("submitContact").toString(), textContentType))                                //联系方式
                .addPart("submitDate", new StringBody(Mapdata.get("submitDate").toString(), textContentType))                                  //日期


        // 检查工单文件
        String FileSQL =  ''' select PATH,UPLOAD_CLASS2_ID from uploadlist where  GUID=? '''
        List<Map<String, Object>> FileSQLSqlList = jt.queryForList(FileSQL,Mapdata.get("clueNo").toString());
        File file1,file2;
        for(int k = 0 ; k < FileSQLSqlList.size();k++){
            // 创建文件对象
            String FilePatch = "/nas/davco_cc/ngs/"+FileSQLSqlList[k].get("PATH");
            String FileType = FileSQLSqlList[k].get("UPLOAD_CLASS2_ID");
            if(FileType.equals("FAKES2")&&file1==null){
                  file1 = new File(FilePatch); // 替换为你的文件路径
                builder.addPart("onlineProductPhoto", new FileBody(file1, textContentType));                        //产品图片
            }else if(FileType.equals("FAKES3")&&file2==null){
                  file2 = new File(FilePatch); // 替换为你的文件路径
                builder.addPart("onlineAccountPhoto", new FileBody(file2, textContentType));                        //帐号图片
            }
        }

        log.debug("参数信息："+builder);
        HttpEntity entity = builder.build();
        // 创建 POST 请求
        HttpPost post = new HttpPost(URL2); // 替换为你的 API 地址
        post.setEntity(entity);
        post.addHeader("P-AUTH-TOKEN", "1ADyBSGt@67012792");

        // 发送请求并获取响应
        HttpResponse response1 = client.execute(post);
        int statusCode = response1.getStatusLine().getStatusCode();
        if (statusCode == 200) {
            String responseBody = EntityUtils.toString(response1.getEntity());
            log.debug("调取结果成功: " + responseBody);
        } else {
            log.debug("调取结果失败: " + statusCode);
        }



    }







}



































